package exemplo.faces;

import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import javax.faces.model.SelectItem;

import exemplo.database.LoginDAO;
import exemplo.database.ProductDAO;
import exemplo.database.SaleDAO;
import exemplo.model.Login;
import exemplo.model.Product;
import exemplo.model.Sale;

public class SalesFace {

	private SaleDAO salesDAO = new SaleDAO();;
	private ProductDAO prodDAO = new ProductDAO();;
	private LoginDAO loginDAO = new LoginDAO();;
	private Sale selectedSale;
	private List<Sale> sales;
	
	public SalesFace() throws Exception{
		System.out.println("My SalesFace has been created!");
	}
	
	public String startAddSale() {
		selectedSale = new Sale();
		return "gotoAddNewSale";
	}
	
	public List<SelectItem> getProducts() {
		List<SelectItem> list = new LinkedList<SelectItem>();
		try {
			for(Product prod : prodDAO.getAllProducts()) {
				list.add(new SelectItem(prod, prod.getName()));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return list;
		
	}
	
	public List<SelectItem> getVendors() {
		List<SelectItem> list = new LinkedList<SelectItem>();
		try {
			for(Login login: loginDAO.getUsers()) {
				list.add(new SelectItem(login, login.getName()));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return list;
		
	}
	
	public String finishAddSale() throws Exception{
		salesDAO.add(selectedSale);
		sales = null;
		return "gotoListSales";
	}
	
	public List<Sale> getSales() throws Exception{
		if (sales == null) {
			sales = salesDAO.getSales();
		}
		return sales;
	}
	
	public String viewSelectedSale() {
		return "gotoViewSelectedSale";
	}
	
	public String removeSale() throws Exception{
		salesDAO.delete(selectedSale);
		sales = null;
		return "gotoListSales";		
	}

	public Sale getSelectedSale() {
		return selectedSale;
	}

	public void setSelectedSale(Sale selectedSale) {
		this.selectedSale = selectedSale;
	}

}
